package com.kungfuhacking.wristbandpro.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.String.valueOf;

/**
 * 工具类
 * Created by Aaron on 17/3/22.
 */

public class CommonUtils {

    /**
     * MD5加密
     *
     * @param bytes 字节数组
     * @return 加密后的值
     */
    public static String toMd5(byte[] bytes) {

        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(bytes);
            return toHexString(algorithm.digest(), "");
        } catch (NoSuchAlgorithmException e) {
            Log.v("util", "toMd5():" + e);
            throw new RuntimeException(e);
        }

    }

    private static String toHexString(byte[] bytes, String separator) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex).append(separator);
        }
        return hexString.toString();
    }

    public static File getCacheDir(Context mContext) {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.WRISTBAND_PRO;
        File myFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!myFile.exists()) {
            myFile.mkdirs();
        }
        return myFile;
    }

    /**
     * 网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager mgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info = mgr.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获得图片的字节
     *
     * @param image
     * @return
     */
    public static byte[] compressByte(Bitmap image) {
        if (image == null)
            return null;
        byte[] bytes = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 质量压缩100% 未压缩
        bytes = baos.toByteArray();
        try {
            baos.close();
        } catch (IOException e) {
            Log.v("图片压缩", e.getMessage());
        }
        return bytes;
    }

    /**
     * 获取文件的字节码
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static byte[] getFileByte(File file) throws Exception {
        byte[] bytes = null;
        if (file != null) {
            InputStream is = new FileInputStream(file);
            long length = file.length();
            if (length > Integer.MAX_VALUE)   //当文件的长度超过了int的最大值
            {
//                System.out.println("this file is max ");
                return null;
            }
            bytes = new byte[(int) length];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            //如果得到的字节长度和file实际的长度不一致就可能出错了
            if (offset < bytes.length) {
//                System.out.println("file length is error");
                return null;
            }
            is.close();
        }
        return bytes;
    }


    /**
     * 获取手机的Ip地址
     */
    public static String getIpAddress(Context context) {
        String ipAddress = null;
        WifiInfo wifiInfo = getWifiInfo(context);
        if (wifiInfo != null)
            ipAddress = intToIpAddress(wifiInfo.getIpAddress());

        return ipAddress;
    }

    /**
     * 获取WifiInfo
     */
    private static WifiInfo getWifiInfo(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = null;
        if (null != wifiManager) {
            info = wifiManager.getConnectionInfo();
        }
        return info;
    }

    private static String intToIpAddress(long ipInt) {
        return valueOf(ipInt & 0xFF) + "." +
                ((ipInt >> 8) & 0xFF) + "." +
                ((ipInt >> 16) & 0xFF) + "." +
                ((ipInt >> 24) & 0xFF);
    }

    /**
     * 根据图片本地地址获得bitmap
     *
     * @param picturePath 图片的本地地址
     * @return
     */
    public static Bitmap getBitmapFromPath(String picturePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        // options 设为true时，构造出的bitmap没有图片，只有一些长宽等配置信息，但比较快，设为false时，才有图片
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(picturePath, options);
        int scale = (int) (options.outWidth / (float) 300);
        if (scale <= 0)
            scale = 1;
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(picturePath, options);
    }


    /**
     * 把bitmap保存到本地 (未压缩)
     *
     * @param bp  图片
     * @param url 本地的路径
     * @return
     */
    public static void saveBitmap2Local(Bitmap bp, String url) throws IOException {

        File file = new File(url);

        if (!file.exists())
            file.createNewFile();

        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bp.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

//    /**
//     * 判断当前聊天是否是群聊
//     *
//     * @param topic
//     * @return
//     */
//    public static boolean isGroupChat(String topic) {
//        return topic.startsWith(MqttConstant.START_GROUP) || topic.startsWith(MqttConstant.START_CHILD);
//    }

    /**
     * 压缩图片
     *
     * @param srcPath 图片的地址
     * @return
     */
    public static Bitmap compressImageFromFile(String srcPath) {

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;//只读边,不读内容
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

        int w = newOpts.outWidth;
        int h = newOpts.outHeight;

        float hh = 0;
        float ww = 0;

        if (w > 1920 || h > 1920) {
            //
            hh = 320f;//
            ww = 240f;//

        } else {
            hh = 800f;//
            ww = 480f;//
        }

        int be = 1;
        if (w > h && w > ww) {
            be = (int) (newOpts.outWidth / ww);
        } else if (w <= h && h > hh) {
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;

        newOpts.inJustDecodeBounds = false;
        newOpts.inSampleSize = be;//设置采样率

        Log.d("CommonUtils", " 压缩比率 : " + be);

        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//
        newOpts.inPurgeable = true;// 同时设置才会有效
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
        return bitmap;
    }


    /**
     * 获得屏幕的尺寸
     *
     * @param ctx 上下文对象
     * @return 屏幕宽高的 数组  0位宽  1为高
     */
    public static int[] getScreenSize(Context ctx) {

        DisplayMetrics metric = new DisplayMetrics();
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）
//        float density = metric.density;      // 屏幕密度（0.75 / 1.0 / 1.5）
//        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）

        int[] sizes = {width, height};

        return sizes;
    }

    /**
     * 查看消息内容是否有含有[]内容
     *
     * @param text
     * @return
     */
    public static boolean isContainEmo(String text) {

        String regEx = ".*\\[[\\u4E00-\\u9FA5]{2}\\].*";
        // 通过传入的正则表达式来生成一个pattern
        Pattern sinaPatten = Pattern.compile(regEx);
        Matcher m = sinaPatten.matcher(text);

        return m.matches();

    }

    /**
     * 提取消息中含有[],且[]里的内容为两个中文 的内容
     *
     * @return
     */
    public static List<String> getEmoList(String str) {

        List<String> maths = new ArrayList<String>();
//        String regEx = ".*\\[[\\u4E00-\\u9FA5]{2}\\].*";
        Pattern p = Pattern.compile("\\[[\\u4E00-\\u9FA5]{2}\\]");
        Matcher m = p.matcher(str);
        while (m.find()) {
            maths.add(m.group());
//            String group = m.group();
//            LogUtil.e("tag", "提取出来的内容:" + m.group());
//            System.out.println(m.group());
        }

        return maths;
    }

//    /**
//     * 判断双方是否是好友,或者是否是群成员 (是否可以发送消息的判断)
//     * 不是好友不能发送消息, 不在群里 不能发送消息
//     *
//     * @return
//     */
//    public static boolean isFriendOrGroupNum(SharedPreferences sp, Context ctx, String topic) {
//
//        if (MqttConstant.topicMap == null)
//            MqttConstant.topicMap = (Map<String, TopicBean>) JSON.parse(sp.getString(MqttConstant.TOPIC_MAP, ""));
//
//        if (MqttConstant.topicMap == null) {
//            Toast.makeText(ctx, "好友数据异常", Toast.LENGTH_SHORT).show();
//            return false;
//        }
//
//        if (!MqttConstant.topicMap.containsKey(topic)) {
//
//            if (isGroupChat(topic)) {
//                Toast.makeText(ctx, "你不是该群的成员", Toast.LENGTH_SHORT).show();
//                return false;
//
//            } else {
//                Toast.makeText(ctx, "对方不是你的好友,请先添加对方为好友", Toast.LENGTH_SHORT).show();
//                return false;
//            }
//
//        }
//
//        return true;
//    }


    /**
     * 将一个对象保存到本地
     *
     * @param name 保存的文件名称
     * @param obj  保存的对象
     * @return void
     */
    public static void fileSave(String name, Object obj) {
        //保存在sd卡
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
            File sdFile = new File(sdCardDir, name);

            try {
                FileOutputStream fos = new FileOutputStream(sdFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(obj);// 写入
                fos.close(); // 关闭输出流
            } catch (Exception e) {
                e.printStackTrace();
            }
            LogUtil.d("Commonutils", "成功保存到sd卡");

        }
    }

    /**
     * 读取本地对象
     *
     * @param name 要获取的名称 key
     */
    public static Object readObj(String name) {

        Object obj = null;
        File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
        File sdFile = new File(sdCardDir, name);

        try {
            FileInputStream fis = new FileInputStream(sdFile);   //获得输入流
            ObjectInputStream ois = new ObjectInputStream(fis);
            obj = (Object) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;

    }


    public static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }




}
